package com.gxh.shirotest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * @author Xiaohong X Gou
 * @createTime 2023-04-11 14:06
 * @description
 */
public class ShiroRun {
    public static void main(String[] args) {
        //1.初始化SecurityManager
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //2.获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //3.创建token对象，web应用用户名密码从页面传递过来
        AuthenticationToken token= new UsernamePasswordToken("zhangsan","z3");
        //4.完成登录;
        try {
            subject.login(token);
            System.out.println("登录成功");
            //5.判断角色
            boolean role1 = subject.hasRole("role1");
            System.out.println("hasRole1="+role1);
            //6.判断权限
            boolean permitted = subject.isPermitted("user:insert");
            System.out.println("是否拥有此权限 =" +permitted);
            subject.checkPermission("user:insert");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            e.getCause();
            e.getMessage();
            System.out.println("登录失败");
        }
    }
}
